#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(OS_ANDROID)||defined(OS_LINUX_SOC)
#include <err.h>
#endif
#include <libmslog/mslog.h>
#include <libmscommon/mscommon.h>
#include "msprotocol.h"

#define  FLAG "PIPE"

static int pipe_create(char *pipename)
{
	unlink(pipename);
	if(mkfifo(pipename,0666)<0){
		return -1;
	}
	return 0;
}

static int pipe_open(URLContext *h)
{
	char *filename=h->url;
//need test linux opt:O_CREAT| O_RDWR|O_APPEND|O_BINARY
#if defined(OS_ANDROID)||defined(OS_LINUX_SOC)	
	h->fd= ms_open(filename, O_CREAT| O_RDWR|h->flags, 0666);
#elif defined(OS_WIN32) 
   	h->fd= ms_open(filename, O_CREAT| O_RDWR|O_APPEND|O_BINARY|h->flags, 0666);
#endif
	return (h->fd == -1) ? (-1) :0;
}

static int pipe_read(URLContext *h, unsigned char *buf, int size)
{
	int fd = h->fd;
	return ms_read(fd, buf, size);
}

static int pipe_write(URLContext *h, unsigned char *buf, int size)
{
	int fd = h->fd;
	return ms_write(fd, buf, size);
}

static int pipe_close(URLContext *h)
{
	int fd = h->fd;
	return ms_close(fd);
}

URLProtocol ffurl_pipe_protocol = {
	.nameDes	= msptc_getPtcNameDes(msptc_pipe),
	.url_open	= pipe_open,
	.url_read	= pipe_read,
	.url_write	= pipe_write,
	.url_close	= pipe_close,
};
